package c.c.d.s.s.o.csd.as.configuration.support.user;

import c.c.d.s.s.o.csd.as.mapper.user.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 自定义的 {@link UserDetailsService}
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-06-22 13:45
 */
@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("About to produce UserDetails with user-name: {}", username);
        return new CustomUserDetails(
                Optional.ofNullable(userMapper.getUser(username)).orElseThrow(() -> new UsernameNotFoundException(String.format("无此用户 (%s)!", username)))
        );
    }

    // ~ Autowired
    // -----------------------------------------------------------------------------------------------------------------

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
